<template>
  <div class="serach-container">
    <!-- 搜索框 -->
    <form action="/">
      <van-search
        v-model="searchText"
        show-action
        background="#3296fa"
        placeholder="请输入搜索关键词"
        @search="onSearch"
        @cancel="onCancel"
        @clear="isResultShow = false"
        @focus="isResultShow = false"
      />
    </form>
    <!-- /搜索框 -->
    <!-- 搜索结果 -->
    <search-result v-if="isResultShow" :q="searchText" />
    <!-- /搜索结果 -->

    <!-- 联想建议 -->
    <search-suggestion
      v-else-if="searchText"
      :search-text="searchText"
      @search="onSearch"
    />
    <!-- /联想建议 -->

    <!-- 搜索历史记录 -->
    <search-history
      v-else
      :search-histories="searchHistories"
      @search="onSearch"
    />
    <!-- /搜索历史记录 -->
  </div>
</template>
<script>
import SearchResult from "./components/search-result.vue";
import searchSuggestion from "./components/search-suggestion.vue";
import SearchHistory from "./components/search-history.vue";
import { setItem, getItem } from "@/utils/storage";
export default {
  components: { searchSuggestion, SearchResult, SearchHistory },
  data() {
    return {
      searchText: "",
      isResultShow: false,
      searchHistories: getItem("TOUTIAO_SEARCH") || []
    };
  },
  watch: {
    searchHistories: {
      deep: true,
      immediate: true,
      handler(val) {
        setItem("TOUTIAO_SEARCH", val);
      }
    }
  },
  methods: {
    onSearch(val) {
      this.searchText = val;
      this.isResultShow = true;
      this.searchHistories.includes(val) || this.searchHistories.unshift(val);
    },
    onCancel() {
      this.$router.back();
    }
  }
};
</script>
<style lang="less" scoped>
.search-container {
  /deep/ .van-search__action {
    color: #fff;
  }
}
</style>
